// 数据库操作
const Op = require('sequelize').Op
const User = require('../models/user.models')


class UserService {
    // 数据库创建员工
    async create(user) {
        // isInnerMember 1: 内部成员 2：外部成员
        const result = await User.create({
            userId: user.userId,
            password: user.password,
            isInnerMember: user.isInnerMember,
            userStatus: user.isInnerMember === 1 ? 1 : 2
        });
        return result
    }
    // 数据库通过userId查询员工
    async getUserById(userId) {
        const result = await User.findAll({
            // attributes: ['userId', 'nickname', 'phone', 'isInnerMember', 'userStatus', ['userStatus', 'status']],
            where: { userId: userId }
        }, 'userId');
        return result
    }
    // 数据库查询员工列表
    async getUserList(params, page, skipIndex) {
        const result = await User.findAndCountAll({
            // attributes: ['userId', 'nickname', 'phone', 'isInnerMember', 'userStatus', ['userStatus', 'status']],
            // order: [['userId', 'DESC']],
            attributes: { exclude: ['password']},
            where: params,
            offset: skipIndex,
            limit: page.pageSize
        });
        return result
    }
    // 批量查询
    async searchAll(userIds) {
        const result = await User.findAndCountAll({
            where: {
                userId: {[Op.in]: userIds}
            }
        });
        return result
    }
    // 批量插入或更新
    async updateUserList(updateList) {
        const result = await User.bulkCreate(updateList, { updateOnDuplicate: ['userStatus'] });
        return result
    }
    // 更新一条数据
    async updateUserInfo(userInfo) {
        const result = await User.update(userInfo, {
            where: {
                userId: userInfo.userId
            }
        });
        return result
    }
}

module.exports = new UserService()